package touro.mancala.client;

import java.util.ArrayList;

public class MoveController {
	private GameState state;
	private Board board;
	private Store[] pits;

	public MoveController() {
		state = GameState.getGameState();
		board = state.getBoard();
		pits = board.getPitsAndStores();
	}

	public String move(Store store) throws Exception
	{
		int index = ((Pit)store).getPlace();
		return move(index);
	}
	
	//returns a String with an output message depending on what sow accomplished
	//if can't move for whatever reason will throw exception with output message
	public String move(int i) throws Exception {
		
		Move move = new Move(i);
		boolean sowAgain = move.sow();
		int gameOver = state.isGameOver();
		String message;
		if (gameOver == -1) {
			if (sowAgain) {
				message = state.getActivePlayer() + " has another turn!";
			} else {
				Player p = state.nextPlayer(); 
				message = p +  "'s turn.";
			}
		} else {
			endGame(gameOver);
			Player winningPlayer = state.mostStones();
			message = "Game Over! " + winningPlayer + " has won!";
		}
		return message;
	}

	private void endGame(int player) {
		ArrayList<Stone> stones;
		player = player*7;
		Store myStore = pits[player + 6];
		for (int i = player; i < player+6; i++) {
			stones = ((Pit)pits[i]).removeStones();
			myStore.addStone(stones);
		}
	}
}
